package com.weishi.project.training.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.enums.TrainingProgramEnum;
import com.weishi.common.utils.StringUtils;
import com.weishi.project.api.ret.SportsManAchievement;
import com.weishi.project.api.ret.TrainingAllDataInfoRet;
import com.weishi.project.api.ret.TrainingDataRet;
import com.weishi.project.api.vo.SportManBestResultVo;
import com.weishi.project.api.vo.TrainingAchievementMaxVo;
import com.weishi.project.api.vo.TrainingAchievementTopVo;
import com.weishi.project.api.vo.TrainingDataVo;
import com.weishi.project.sport.trainingdata.vo.WaterRankingVO;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.mapper.TrainingAchievementMapper;
import com.weishi.project.training.mapper.TrainingDayMapper;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TrainingAchievementService业务层处理
 */
@Service
public class TrainingAchievementServiceImpl extends ServiceImpl<TrainingAchievementMapper, TrainingAchievement> implements ITrainingAchievementService {

    @Autowired
    private TrainingAchievementMapper trainingAchievementMapper;

    @Autowired
    private TrainingDayMapper trainingDayMapper;

    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 陆上分段 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;

    /**
     * 水上分段 接口
     */
    @Autowired
    private IHeartRateCountService heartRateCountService;

    /**
     * 水上分段心率 接口
     */
    @Autowired
    private IHeartRateRecordService heartRateRecordService;



    /**
     * 查询TrainingAchievement列表
     */
    @Override
    public List<TrainingAchievement> selectTrainingAchievementList(TrainingAchievement trainingAchievement) {
        return trainingAchievementMapper.selectTrainingAchievementList(trainingAchievement);
    }

    @Override
    public List<AchievementExcel> selectTrainingAchievementListExcel(TrainingAchievement trainingAchievement) {
        return trainingAchievementMapper.selectTrainingAchievementListExcel(trainingAchievement);
    }

    @Override
    public List<TrainingAchievement> selectTrainingAchievementList1(TrainingAchievement trainingAchievement) {
        return trainingAchievementMapper.selectTrainingAchievementList1(trainingAchievement);
    }

    @Override
    public List<Map<String, Object>> qryBestResultSpecialProject(SportManBestResultVo sportManBestResultVo) {
        return trainingAchievementMapper.qryBestResultSpecialProject(sportManBestResultVo);
    }

    @Override
    public TrainingDataRet qryTrainingDataInfoByTrainingDay(int trainingDayId) {
        TrainingDataRet trainingDataRet = null;
        TrainingDay trainingDay =trainingDayMapper.selectById(trainingDayId);
        if(trainingDay!=null){
            trainingDataRet = TrainingDataRet.getInstan(trainingDay);
            List<SportsManAchievement> list = trainingAchievementMapper.qryTrainingAchievementByTrainingDayId(trainingDay.getId());
            trainingDataRet.setSportsMans(list);
        }
        return trainingDataRet;
    }

    @Override
    public List<Map<String, Object>> qryTrainingDataInfoBySportManId(Map<String, Object> params) {
        return trainingAchievementMapper.qryTrainingDataInfoBySportManId(params);
    }

    @Override
    public List<TrainingAchievementTopVo> qryTrainingAchievementTop(Map<String, Object> params) {

        List<TrainingGroupChannel> trainingGroupChannelList = trainingGroupChannelService.qryBestTop10(params,true);

        List<TrainingAchievementTopVo>  ret = new ArrayList<>();
        for(TrainingGroupChannel trainingGroupChannel : trainingGroupChannelList){
            TrainingAchievementTopVo vo = new TrainingAchievementTopVo();
            vo.setAchievement(trainingGroupChannel.getAchievement());
            vo.setChannelId(trainingGroupChannel.getId());
            vo.setBoatType(trainingGroupChannel.getBoatType());
            vo.setPropellerFrequency(trainingGroupChannel.getPropellerFrequency());
            List<TrainingAchievement> persons = trainingGroupChannel.getPerson();
            if(persons!=null && persons.size()>0){
                TrainingAchievement trainingAchievement = persons.get(0);
                String sportsmanName = sportsmanService.qrySportsmanByCache(trainingAchievement.getSportsmanId()).getName();
                if(persons.size()==1){
                    vo.setName(sportsmanName);
                    vo.setHeartRate(trainingAchievement.getHeartRate());
                    vo.setLacticAcid(trainingAchievement.getLacticAcid());
                    vo.setId(trainingAchievement.getId());
                }else {
                    vo.setId(trainingAchievement.getId());
                    vo.setName(sportsmanName+"...");
                }
            }
            ret.add(vo);
        }
        return ret;
    }


    @Override
    public List<TrainingAchievementMaxVo> selectTrainingAchievementListByChannelId(int channelId) {
        return trainingAchievementMapper.selectTrainingAchievementListByChannelId(channelId);
    }

    @Override
    public List<Map<String, Object>> selectClassHourBoatType(Integer sportsManId) {
        Map<String,Object> params = new HashMap<>();
        params.put("sportsManId",sportsManId);
        return trainingAchievementMapper.selectClassHourBoatType(params);
    }

    @Override
    public List<Map<String, Object>> selectKilometersBoatType(Map<String, Object> params) {
        return trainingAchievementMapper.selectKilometersBoatType(params);
    }

    @Override
    public List<TrainingAchievement> trainingAchievementList(Map<String, Object> params) {
        return trainingAchievementMapper.trainingAchievementList(params);
    }

    @Override
    public void updateTrainingAchievement(TrainingAchievement trainingAchievement) {
        trainingAchievementMapper.updateTrainingAchievement(trainingAchievement);
    }

    @Override
    public void deleteTrainingAchievement(TrainingAchievement trainingAchievement) {
        trainingAchievementMapper.deleteTrainingAchievement(trainingAchievement);
    }

    @Override
    public void saveTrainingAchievement(TrainingAchievement trainingAchievement) {
        trainingAchievementMapper.saveTrainingAchievement(trainingAchievement);
    }

    @Override
    public String selectSportsmanNameById(int sportsmanId) {
        return trainingAchievementMapper.selectSportsmanNameById(sportsmanId);
    }

    @Override
    public TrainingAllDataInfoRet qryTrainingAchievementDetailedReport(Integer trainingAchievementId, Integer type) {
        TrainingAllDataInfoRet ret = new TrainingAllDataInfoRet();
        Map<String,Object> params = new HashMap<> ();
        params.put("type",type==1?"special_training_water":"land_specific_training_dynamometer");
        params.put("trainingAchievementId",trainingAchievementId);
        Map<String,Object> retMap = trainingAchievementMapper.selectTrainingAchievementDetailedReport(params);
        if(retMap!=null){
            TrainingAllDataInfoRet.BaseInfo baseInfo = ret.getBaseInfo();
            if(retMap.get("boatType")!=null) baseInfo.setBoatType(retMap.get("boatType").toString());
            if(retMap.get("firstLevel")!=null) baseInfo.setFirstLevel(retMap.get("firstLevel").toString());
            if(retMap.get("secondLevel")!=null) baseInfo.setSecondLevel(retMap.get("secondLevel").toString());
            if(retMap.get("sportsmanId")!=null) baseInfo.setSportsmanName(sportsmanService.qrySportsmanByCache((Integer) retMap.get("sportsmanId")).getName());
            baseInfo.setSportsmanId(Integer.parseInt(retMap.get("sportsmanId").toString()));
            if(retMap.get("day")!=null) baseInfo.setTrainingDay(retMap.get("day").toString());
            if(retMap.get("groupName")!=null) baseInfo.setGroupName(retMap.get("groupName").toString());

            TrainingAllDataInfoRet.AchievementInfo achievementInfo = ret.getAchievementInfo();
            if(retMap.get("id")!=null) achievementInfo.setId(retMap.get("id").toString());
            if(retMap.get("achievement")!=null) achievementInfo.setAchievement(retMap.get("achievement").toString());
            if(retMap.get("watt")!=null)
            {
                achievementInfo.setWatt(retMap.get("watt").toString());
            }else{
                achievementInfo.setWatt(null);
            }
            if(retMap.get("power")!=null)
            {
                achievementInfo.setPower(retMap.get("power").toString());
            }else{
                achievementInfo.setPower(null);
            }
            if(retMap.get("rowingKilometers")!=null) achievementInfo.setRowingKilometers(retMap.get("rowingKilometers").toString());
            if(retMap.get("segmentedTiming")!=null) achievementInfo.setSegmentedTimings(retMap.get("segmentedTiming").toString());

            TrainingAllDataInfoRet.TrainingGroundInfo training = ret.getTrainingGroundInfo();
            if(retMap.get("airTemperature")!=null)
            {
                training.setAirTemperature(retMap.get("airTemperature").toString());
            } else{
                training.setAirTemperature(null);
            }
            if(retMap.get("siteFactors")!=null)
            {
                training.setSiteFactors(retMap.get("siteFactors").toString());
            }else{
                training.setSiteFactors(null);
            }

            if(retMap.get("weather")!=null)
            {
                training.setWeather(retMap.get("weather").toString());
            }else{
                training.setWeather(null);
            }
            if(retMap.get("windSpeed")!=null)
            {
                training.setWindSpeed(retMap.get("windSpeed").toString());
            }else{
                training.setWindSpeed(null);
            }
            List<Map<String,Object>>  sportsManHRs = new ArrayList<>();
            List<Map<String,Object>>  sportsManLAs = new ArrayList<>();
            TrainingAchievement trainingAchievement = new TrainingAchievement();
            if(retMap.get("channelId")!=null) trainingAchievement.setChannelId(Integer.parseInt(retMap.get("channelId").toString()));
            List<TrainingAchievement> trainingAchievements = trainingAchievementMapper.selectTrainingAchievementList(trainingAchievement);
            for(TrainingAchievement achievement : trainingAchievements){
                Map<String,Object> mapHr = new HashMap<>();
                Map<String,Object> mapLa = new HashMap<>();

                Sportsman sportsman = sportsmanService.qrySportsmanByCache(achievement.getSportsmanId());
                mapHr.put("sportsmanName",sportsman.getName());
                mapHr.put("sportsmanId" , sportsman.getId());
                mapHr.put("groupId" , achievement.getGroupId());
                mapHr.put("channelId" , achievement.getChannelId());
                mapHr.put("shipSpeedId" , achievement.getShipSpeedId());
                mapHr.put("trainingDayId" , achievement.getTrainingDayId());
                if(achievement.getPosition()!=null) mapHr.put("position",achievement.getPosition()==-1?"舵手":achievement.getPosition()+"号位");

                // 重新赋值心率
                // 判断水上或者陆上
                if(type == 1){
                    // 查询水上数据
                    List<HeartRateCount> heartRateCountList = heartRateCountService
                            .listZHKID(achievement.getChannelId());
                    int size = heartRateCountList.size();
                    // 平均心率
                    Integer heartRate = 0;

                    // 平均桨频
                    Integer propellerFrequency = 0;
                    for (int j = 0; j<size; j++){
                        propellerFrequency += heartRateCountList.get(j).getPropellerFrequency()==null?0 : Integer.parseInt(heartRateCountList.get(j).getPropellerFrequency());

                        // 查询水上心率
                        List<HeartRateRecord> heartRateRecordList = heartRateRecordService
                                .listRS(heartRateCountList.get(j).getId() , achievement.getSportsmanId());
                        for(int k = 0; k<heartRateRecordList.size(); k++){
                            if(StringUtils.isNotNull(heartRateRecordList.get(k).getHeartRateAvg())){
                                heartRate += heartRateRecordList.get(k).getHeartRateAvg();
                            }
                        }
                    }

                    if(size > 0 && propellerFrequency > 0){
                        Integer propellerFrequencys = propellerFrequency / size;
                        achievementInfo.setPropellerFrequency(propellerFrequencys.toString());
                    }

                    // 存储平均心率
                    List<String> heartRates2List = new ArrayList<>();
                    if(heartRate > 0){
                        Integer heartRates = heartRate / size;
                        String heartRates2 = heartRates.toString();
                        heartRates2List.add(heartRates2);
                        mapHr.put("HRs",heartRates2List);
                    }else{
                        mapHr.put("HRs",heartRates2List);
                    }
                }else{
                    // 查询陆上数据
                    List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                            .listZHKID(achievement.getGroupId() , achievement.getChannelId() , achievement.getTrainingDayId());
                    int size = dynamometerSubsectionList.size();
                    // 平均心率
                    Integer heartRate = 0;

                    // 平均桨频
                    Integer propellerFrequency = 0;
                    for (int j = 0; j<size; j++){
                        if(StringUtils.isNotNull(dynamometerSubsectionList.get(j).getHeartRate()) && !"".equals(dynamometerSubsectionList.get(j).getHeartRate())){
                            heartRate += dynamometerSubsectionList.get(j).getHeartRate();
                            propellerFrequency += Integer.parseInt(dynamometerSubsectionList.get(j).getPropellerFrequency());
                        }
                    }

                    // 存储平均桨频
                    if(size > 0 && propellerFrequency > 0){
                        Integer propellerFrequencys = propellerFrequency / size;
                        achievementInfo.setPropellerFrequency(propellerFrequencys.toString());
                    }

                    // 存储平均心率
                    List<String> heartRates2List = new ArrayList<>();
                    if(heartRate > 0){
                        Integer heartRates = heartRate / size;
                        String heartRates2 = heartRates.toString();
                        heartRates2List.add(heartRates2);
                        mapHr.put("HRs",heartRates2List);
                    }else{
                        mapHr.put("HRs",heartRates2List);
                    }
                }

                if(achievement.getId()!=null) mapHr.put("memo",achievement.getId());

                mapLa.put("sportsmanName",sportsman.getName());
                mapLa.put("sportsmanId" , sportsman.getId());
                mapLa.put("groupId" , achievement.getGroupId());
                mapLa.put("channelId" , achievement.getChannelId());
                mapLa.put("shipSpeedId" , achievement.getShipSpeedId());
                mapLa.put("trainingDayId" , achievement.getTrainingDayId());
                if(achievement.getPosition()!=null) mapLa.put("position",achievement.getPosition()==-1?"舵手":achievement.getPosition()+"号位");
                if(achievement.getLacticAcid()!=null) {
                    mapLa.put("LAs",achievement.getLacticAcid().split(","));
                }else{
                    mapLa.put("LAs","".split(","));
                }
                if(achievement.getId()!=null) mapLa.put("memo",achievement.getId());

                sportsManHRs.add(mapHr);
                sportsManLAs.add(mapLa);
            }
            ret.setSportsManHRs(sportsManHRs);
            ret.setSportsManLAs(sportsManLAs);
        }
        return ret;
    }

    @Override
    public List<Map<String, Object>> qryDetailedReportByParams(TrainingDataVo trainingDataVo) {
        List<Integer> sportsmanIds = trainingDataVo.getSportsmanIds();
        List<Integer> sportswomanIds = trainingDataVo.getSportswomanIds();

        if(sportswomanIds!=null && sportswomanIds.size()!=0 && sportswomanIds.get(0)==-1){
            //女 1
            sportswomanIds = this.sportsmanService.selectSportsmanIdListBySex(1);
        }
        if(sportsmanIds!=null && sportsmanIds.size()!=0 && sportsmanIds.get(0)==-1){
            //男 0
            sportsmanIds = this.sportsmanService.selectSportsmanIdListBySex(0);
        }

        if(sportsmanIds==null || sportsmanIds.size()==0){
            sportsmanIds = new ArrayList<>();
        }
        if(sportswomanIds!=null && sportswomanIds.size()>0){
            sportsmanIds.addAll(sportswomanIds);
        }
        trainingDataVo.setSportsmanIds(sportsmanIds);

        List<Map<String, Object>> maps = trainingAchievementMapper.selectDetailedReportByParams(trainingDataVo);

        int size = maps.size();
        for (int i = 0; i<size; i++){
            // 查询训练成绩表数据
            TrainingAchievement trainingAchievement = this.getById(Integer.parseInt(maps.get(i).get("id").toString()));

            // 判断水上陆上
            if(trainingDataVo.getFirstLevel().equals(TrainingProgramEnum.WATERPROJECT.getKey())){
                // 水上数据
                // 查询水上数据
                List<HeartRateCount> heartRateCountList = heartRateCountService
                        .listZHKID(trainingAchievement.getChannelId());
                int sizes = heartRateCountList.size();
                // 平均心率
                Integer heartRate = 0;
                for (int j = 0; j<sizes; j++){
                    // 查询水上心率
                    List<HeartRateRecord> heartRateRecordList = heartRateRecordService
                            .listRS(heartRateCountList.get(j).getId() , trainingAchievement.getSportsmanId());
                    for(int k = 0; k<heartRateRecordList.size(); k++){
                        if(StringUtils.isNotNull(heartRateRecordList.get(k).getHeartRateAvg())){
                            heartRate += heartRateRecordList.get(k).getHeartRateAvg();
                        }
                    }
                }
                if(sizes>0 && StringUtils.isNotNull(heartRate) && !"".equals(heartRate)){
                    Integer heartRates = heartRate / sizes;
                    maps.get(i).put("heartRate" , heartRates.toString());
                }
            }else{
                // 陆上数据
                // 查询陆上分段心率数据
                List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                        .listZHKID(trainingAchievement.getGroupId() , trainingAchievement.getChannelId() , trainingAchievement.getTrainingDayId());
                int sizes = dynamometerSubsectionList.size();
                // 平均心率
                Integer heartRate = 0;
                for (int j = 0; j<sizes; j++){
                    if(StringUtils.isNotNull(dynamometerSubsectionList.get(j).getHeartRate()) && !"".equals(dynamometerSubsectionList.get(j).getHeartRate())){
                        heartRate += dynamometerSubsectionList.get(j).getHeartRate();
                    }
                }
                if(StringUtils.isNotNull(heartRate) && !"".equals(heartRate)){
                    Integer heartRates = heartRate / sizes;
                    maps.get(i).put("heartRate" , heartRates.toString());
                }
            }
        }
        return maps;
    }

    @Override
    public boolean updateById(TrainingAchievement entity) {
        return super.updateById(entity);
    }



    /**
     * 查询运动员水上专项训练--最好成绩排名
     */
    @Override
    public List<WaterRankingVO> getWaterRankingVO(Integer userId , Integer trainingMode , Integer kilometers , Integer sex , Integer realClassHour) {
        return trainingAchievementMapper.getWaterRankingVO(userId , trainingMode , kilometers , sex , realClassHour);
    }


    /**
     * 查询运动员水上专项训练--根据 运动员名称查询排名
     */
    @Override
    public List<WaterRankingVO> getWaterRankingNameVO(String name , Integer trainingMode, Integer kilometers , Integer sex , Integer realClassHour) {
        return trainingAchievementMapper.getWaterRankingNameVO(name , trainingMode , kilometers , sex , realClassHour);
    }


    /**
     * 查询运动员陆上专项训练--最好成绩排名
     */
    @Override
    public List<WaterRankingVO> getWaterRankingVOLU(Integer userId, Integer trainingMode, Integer kilometers , Integer sex , Integer realClassHour) {
        return trainingAchievementMapper.getWaterRankingVOLU(userId , trainingMode , kilometers , sex , realClassHour);
    }


    /**
     * 查询运动员专项训练--根据 运动员名称查询排名
     */
    @Override
    public List<WaterRankingVO> getWaterRankingNameVOLU(String name, Integer trainingMode, Integer kilometers , Integer sex , Integer realClassHour) {
        return trainingAchievementMapper.getWaterRankingNameVOLU(name , trainingMode , kilometers , sex , realClassHour);
    }


    /**
     * 运动员 -- 今日专项成绩排名 第一次查询
     */
    @Override
    public List<WaterRankingVO> getThisDayRankingVO(Integer groupId  , String boatType , Integer trainingDayId, Integer sex, Integer trainingMode , Integer kilometers , Double realClassHour , String firstLevel) {
        return trainingAchievementMapper.getThisDayRankingVO(groupId , boatType , trainingDayId , sex , trainingMode , kilometers , realClassHour , firstLevel);
    }


    /**
     * 查询运动员陆上专项训练--根据 运动员名称查询排名 第二次查询
     */
    @Override
    public List<WaterRankingVO> getThisDayRankingVOSS(Integer groupId , String firstLevel , String name, Integer trainingMode, Integer kilometers, Integer sex) {
        return trainingAchievementMapper.getThisDayRankingVOSS(groupId , firstLevel , name , trainingMode , kilometers , sex);
    }

    @Override
    public void deleteTrainingAchievementByChannelId(Integer channelId) {
        trainingAchievementMapper.deleteTrainingAchievementByChannelId(channelId);
    }

    @Override
    public List<TrainingAchievementTopVo> qryTrainingAchievementTopGroupByBoat(Map<String, Object> params) {
        List<TrainingAchievementTopVo> list = trainingAchievementMapper.qryTrainingAchievementTopGroupByBoat(params);
        for(TrainingAchievementTopVo vo : list){
            TrainingAchievement param = new TrainingAchievement();
            param.setChannelId(vo.getChannelId());
            List<TrainingAchievement> list1 = trainingAchievementMapper.selectTrainingAchievementList1(param);
            List<String> sportNames = new ArrayList<>();
            for(TrainingAchievement achievement : list1){
                sportNames.add(achievement.getSportsmanName());
            }
            vo.setSportNames(sportNames);
        }
        return list;
    }



    /**
     * 根据成绩表查询今天参加的所有课程 id
     */
    @Override
    public List<Integer> getIdList(Integer userId, String day) {
        return trainingAchievementMapper.getIdList(userId , day);
    }






}